<?php
declare (strict_types = 1);
namespace app\user\logic\user;

use app\admin\logic\system\Config as SystemConfig;
use app\common\exception\LogicException;
use GuzzleHttp\Client;
use think\helper\Str;

/**
 * 网易易盾接口类
 */
class Oneclick
{
    protected $uri = 'https://ye.dun.163yun.com/v1/oneclick/check';

    /**
     * 网易易盾检查手机号
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-09
     */
    public function check($token, $accessToken)
    {
        $oneclick_conf = SystemConfig::get('system.login.oneclick', ['secretId' => '', 'secretKey' => '', 'businessId' => ''], request()->mhm_id);
        if (in_array('', $oneclick_conf)) {
            throw new LogicException('登录失败','请配置正确的网易易盾参数');
        }
        $time = intval(microtime(true) * 1000);

        $params = [
            'secretId'    => $oneclick_conf['secretId'],
            'businessId'  => $oneclick_conf['businessId'],
            'version'     => 'v1',
            'timestamp'   => $time,
            'nonce'       => Str::random(32),
            'token'       => $token,
            'accessToken' => $accessToken,
        ];
        $params['signature'] = $this->signature($oneclick_conf['secretKey'], $params);
        $client              = new Client();
        $res                 = $client->request('post', $this->uri, ['form_params' => $params]);
        $response            = $res->getBody()->getContents();
        $response            = json_decode($response);
        if ($response->code != 200) throw new LogicException('登录失败', $response->msg);

        return $response->data->phone;
    }

    /**
     * 生成签名算法
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-08
     */
    public function signature($secretKey, $params): string
    {
        ksort($params);
        $buff = "";
        foreach ($params as $key => $value) {
            $buff .= $key;
            $buff .= $value;
        }
        $buff .= $secretKey;
        return md5(mb_convert_encoding($buff, "utf8", "auto"));
    }
}
